clc;clear;clearvars;
% 随机生成5个数据
num_initial = 5;
num_vari = 5;
% 每个变量编码的长度
len_vari = 10;
% 搜索区间
upper_bound = 32;
lower_bound = -32;
iter = 3000;
w = 1;
% 随机生成5个数据,并获得其评估值
sample_x = init_sample(num_initial, num_vari, len_vari);
decode_sample_x = decode(sample_x, num_initial, num_vari, len_vari, upper_bound, lower_bound);
sample_y = F2(decode_sample_x);
Fmin = zeros(iter, 1);
aver_Fmin = zeros(iter, 1);

for n = 1 : 100
    k = 1;
    % 初始化一些参数
    pbestx = sample_x;
    pbesty = sample_y;
    % 当前位置信息presentx
    presentx = init_sample(num_initial, num_vari, len_vari);
    vx = sample_x;
    [fmin, gbest] = min(pbesty);
    fprintf("iter 0 fmin: %.4f\n", fmin);
    for i = 1 : iter
        r1 = rand(num_initial, num_vari, len_vari);
        % pso更新下一步的位置
        vx = w.*vx + 2 * r1 .* (pbestx - presentx) + 2 * r1 .* (pbestx(gbest, :, :) - presentx);
        % vx设置边界目的是为了使s在0~1之间
        vx(vx > 10) = 10;
        vx(vx < -10) = -10;
        s = 1 ./ (1 + exp(-vx));
        r2 = rand(num_initial, num_vari, len_vari);
        presentx(r2 < s) = 1;
        presentx(r2 >= s) = 0;
        % 解码
        decode_presentx = decode(presentx, num_initial, num_vari, len_vari, upper_bound, lower_bound);
        presenty = F2(decode_presentx);
        % 更新每个单独个体最佳位置
        pbestx(presenty < pbesty, :, :) = presentx(presenty < pbesty, :, :);
        decode_pbestx = decode(pbestx, num_initial, num_vari, len_vari, upper_bound, lower_bound);
        pbesty = F2(decode_pbestx);
        % 更新所有个体最佳位置
        [fmin, gbest] = min(pbesty);
        if mod(i,100) == 0
            fprintf("iter %d fmin: %.4f\n", i, fmin);
        end
        Fmin(k, 1) = fmin;
        k = k +1;
    end
    aver_Fmin = aver_Fmin + Fmin;
end
aver_Fmin = aver_Fmin ./ 100;
disp(decode_pbestx(gbest, :));
plot(aver_Fmin);